package net.wantongtech.xa.uploadbasicinfo.service;

import com.google.common.io.Files;
import com.wtkj.exception.BusinessException;
import com.wtkj.vo.dzzf.base.xxjh.MessageSend;
import com.wtkj.zwxt.enums.SignSourceEnum;
import com.wtkj.zwxt.tool.RandomGUID;
import lombok.extern.slf4j.Slf4j;
import net.wantongtech.xa.uploadbasicinfo.dao.CommonBaseDao;
import org.apache.commons.lang.ArrayUtils;
import org.joda.time.LocalDate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 导入批量扣款数据
 *
 * @author MaShibo
 * 日期 :  2020/1/15
 */
@Service
@Slf4j
public class ImportBatchDataService {

    @Resource
    private CommonBaseDao commonBaseDao;
    private Charset charset = Charset.forName("UTF-8");


    @SuppressWarnings("UnstableApiUsage")
    @Transactional(rollbackFor = Throwable.class)
    public void importData() {
        File dir = new File("C:\\Users\\Administrator\\Desktop\\dealWith");
        File[] jsonFiles = dir.listFiles((dir1, name) -> name.endsWith(".json"));
        if (ArrayUtils.isEmpty(jsonFiles)) {
            log.info("未获取到json文件");
            return;
        }
        Date createOn = LocalDate.parse("2020-01-15").toDate();
        log.info("共{}个json文件", jsonFiles.length);
        List<MessageSend> messageSendList = Arrays.stream(jsonFiles)
                .map(jsonFile -> {
                    String name = jsonFile.getName();
                    String withOutExtName = name.substring(0, name.lastIndexOf('.'));
                    String[] splits = withOutExtName.split("-");
                    String channelType = splits[0];
                    long msgId = Long.parseLong(splits[1]);
                    log.info("渠道编号：{}，msgId：{}", channelType, msgId);
                    MessageSend messageSend = new MessageSend();
                    messageSend.setSend(11);
                    messageSend.setListId(new RandomGUID().toString());
                    messageSend.setChannelType(channelType);
                    messageSend.setSignSource(SignSourceEnum.APP.getSource());
                    try {
                        String msgBody = Files.toString(jsonFile, charset);
                        messageSend.setMsgBody(msgBody);
                    } catch (Exception e) {
                        throw new BusinessException("解析失败");
                    }
                    messageSend.setCreateOn(createOn);
                    messageSend.setMsgId(msgId);
                    return messageSend;
                }).collect(Collectors.toList());
        messageSendList.forEach(messageSend -> commonBaseDao.createValueObject(messageSend));
    }

}
